package com.jet.core.validation;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.jet.core.annotation.Password;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * @author dcl
 * @since 2025/3/14 18:31
 */
public class PasswordValidator implements ConstraintValidator<Password, CharSequence> {

    public static final String DEFAULT_REGEX = "^(?=.*[a-zA-Z])(?=.*\\d).{6,18}$";
    private String regex;

    @Override
    public void initialize(Password constraintAnnotation) {
        regex = constraintAnnotation.regex();
        if (StrUtil.isBlank(regex)) {
            regex = DEFAULT_REGEX;
        }
    }

    @Override
    public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
        if (Objects.isNull(value)) {
            return true;
        }
        return Validator.isMatchRegex(regex, value);
    }
}
